<template>
  <a
    v-if="props.fileKey != undefined && props.fileKey > 0"
    href="#DownloadFile"
    @click="downloadFile"
    >{{ props.fileName }}</a
  >
  <span v-else></span>
</template>
<script setup>
import CommonDefine from "@/component/CommonDefine";

const props = defineProps({ fileKey: Number, fileName: String });

const downloadFile = () => {
  fetch(`/api/v1/common/download-file/${props.fileKey}`, {
    headers: {
      Authorization: `Bearer ${localStorage.getItem("token")}`,
    },
  })
    .then((res) => res.blob())
    .then((blob) => {
      var a = document.createElement("a");
      var href = window.URL.createObjectURL(blob); //创建下载的链接
      a.href = href;
      a.download = props.fileName;
      document.body.appendChild(a);
      a.click(); //点击下载
      document.body.removeChild(a); //下载完成移除元素
      window.URL.revokeObjectURL(href); //释放掉blob对象
    })
    .catch((e) => {
      CommonDefine.axiosErrorHandler(e);
    });
};
</script>
